import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms

# 超参数设置
num_epochs = 30        # 增加训练的轮数
batch_size = 100       # 批处理大小
learning_rate = 0.001  # 学习率

# 数据增强：使用随机裁剪、水平翻转等
transform_train = transforms.Compose([
    transforms.RandomCrop(32, padding=4),    # 随机裁剪和填充
    transforms.RandomHorizontalFlip(),        # 随机水平翻转
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

# 仅进行归一化的测试集预处理
transform_test = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

# 下载并加载训练集
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                        download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
                                          shuffle=True, num_workers=0)

# 下载并加载测试集
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
                                       download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
                                         shuffle=False, num_workers=0)

# CIFAR10 的类别标签
classes = ('plane', 'car', 'bird', 'cat', 'deer',
           'dog', 'frog', 'horse', 'ship', 'truck')

# 定义一个改进后的卷积神经网络
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # 第一层卷积：输入通道3，输出通道64，卷积核大小3x3
        self.conv1 = nn.Conv2d(3, 64, 3, padding=1)
        # 第二层卷积：输入通道64，输出通道128，卷积核大小3x3
        self.conv2 = nn.Conv2d(64, 128, 3, padding=1)
        # 第三层卷积：输入通道128，输出通道256，卷积核大小3x3
        self.conv3 = nn.Conv2d(128, 256, 3, padding=1)

        # 池化层：采用2x2的最大池化
        self.pool = nn.MaxPool2d(2, 2)

        # 批归一化层
        self.bn1 = nn.BatchNorm2d(64)
        self.bn2 = nn.BatchNorm2d(128)
        self.bn3 = nn.BatchNorm2d(256)

        # 全连接层
        self.fc1 = nn.Linear(256 * 4 * 4, 512)
        self.fc2 = nn.Linear(512, 256)
        self.fc3 = nn.Linear(256, 10)

    def forward(self, x):
        # 卷积 -> 批归一化 -> ReLU激活 -> 池化
        x = self.pool(F.relu(self.bn1(self.conv1(x))))
        x = self.pool(F.relu(self.bn2(self.conv2(x))))
        x = self.pool(F.relu(self.bn3(self.conv3(x))))

        # 展平操作
        x = x.view(-1, 256 * 4 * 4)

        # 全连接层+激活
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))

        # 输出层
        x = self.fc3(x)
        return x

# 选择运行设备：GPU（如果可用）或CPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
net = Net().to(device)

# 使用Adam优化器
optimizer = optim.Adam(net.parameters(), lr=learning_rate)

# 定义损失函数
criterion = nn.CrossEntropyLoss()

# 训练过程
for epoch in range(num_epochs):
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # 获取输入数据
        inputs, labels = data
        inputs, labels = inputs.to(device), labels.to(device)

        # 梯度置零
        optimizer.zero_grad()

        # 前向传播
        outputs = net(inputs)
        loss = criterion(outputs, labels)

        # 反向传播与优化
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if i % 100 == 99:  # 每100个小批量输出一次loss
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 100))
            running_loss = 0.0

print('训练结束')

# 在测试集上进行测试
correct = 0
total = 0
with torch.no_grad():
    for data in testloader:
        images, labels = data
        images, labels = images.to(device), labels.to(device)
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print('网络在 10000 张测试图片上的准确率为: %.2f %%' % (100 * correct / total))
